#include <iostream>
using namespace std;
#define For(i,a,b) for(int i=(a);i<=(b);++i)
const int M=10000+5,N=100+5;
struct node{
    int num[N];
    int step[N];
}q[M];
int m,n,now,ans,be[M];
int main(){
    cin>>m>>n;
    For(i,1,m){
    	int t=0;
    	For(j,0,n-1){
            cin>>q[i].num[j]>>q[i].step[j];
            if(q[i].num[j])++t;
        }
        be[i]=t;
    }
    cin>>now;
    For(i,1,m){
        ans+=q[i].step[now];
        ans%=20123;
        int p=q[i].step[now]%be[i];
        if(p==0)p=be[i];
        int m=0;
        while(m<=p){
        	
        	m+=q[i].num[now];
        	if(m==p)break;
            now=(now+1)%n;
        }
    }
    cout<<ans<<endl;
    return 0;
}
